package cn.wolfcode.wms.web.controller;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.JSONResult;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Optional;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ISystemMenuService systemMenuService;
    @RequestMapping("list")
    public String list(@ModelAttribute("qo")QueryObject qo, Model model){
        PageResult result = roleService.query(qo);
        model.addAttribute("result",result);
        return "role/list";
    }
    @RequestMapping("input")
    public String input(Long id,Model model){
        //无论是新增还是修改都要将所有权限信息共享到复选框中去
        model.addAttribute("permissions",permissionService.list());
        //共享菜单信息
        model.addAttribute("menus",systemMenuService.list());
        if (Optional.ofNullable(id).isPresent()) {
            model.addAttribute("entity",roleService.get(id));
        }
        return "role/input";
    }

    @RequiredPermission("删除角色")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Long id){
        if (Optional.ofNullable(id).isPresent()) {
            roleService.delete(id);
        }
        return new JSONResult();
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Role entity,Long[] permissionIds,Long[] menuIds){
        roleService.saveOrUpdate(entity,permissionIds,menuIds);
        return new JSONResult();
    }
}
